//! 简化的事件分发器实现
//! 专为测试设计，避免复杂的内存管理问题

use crate::event::{DynamicEvent, DynamicEventHandler/*, EventResult*/};
use crate::core::concurrency::LockFreeMPMCQueue;
use crate::core::concurrency::queue::MPMCQueue;

use std::sync::{Arc, RwLock};
use fxhash::FxHashMap;
use std::thread;
use std::time::Duration;
use std::sync::atomic::{AtomicBool/*, AtomicU64*/, Ordering};

/// 简化的分发器配置
#[derive(Debug, Clone)]
pub struct SimpleDispatcherConfig {
    pub worker_count: usize,
}

impl Default for SimpleDispatcherConfig {
    fn default() -> Self {
        Self {
            worker_count: 2,
        }
    }
}

/// 简化的事件分发器
pub struct SimpleEventDispatcher {
    config: SimpleDispatcherConfig,
    event_queue: Arc<LockFreeMPMCQueue<DynamicEvent>>,
    handlers: Arc<RwLock<FxHashMap<String, Vec<Arc<dyn DynamicEventHandler>>>>>,
    running: Arc<AtomicBool>,
    worker_handles: Vec<thread::JoinHandle<()>>,
}

/// 简化的发送器
#[derive(Clone)]
pub struct SimpleEventSender {
    event_queue: Arc<LockFreeMPMCQueue<DynamicEvent>>,
}

impl SimpleEventSender {
    pub fn publish(&self, event: DynamicEvent) -> Result<(), DynamicEvent> {
        self.event_queue.enqueue(event)
    }
}

impl SimpleEventDispatcher {
    pub fn new(config: SimpleDispatcherConfig) -> Self {
        Self {
            config,
            event_queue: Arc::new(LockFreeMPMCQueue::new()),
            handlers: Arc::new(RwLock::new(FxHashMap::default())),
            running: Arc::new(AtomicBool::new(false)),
            worker_handles: Vec::new(),
        }
    }

    pub fn register_handler(&mut self, event_type: &str, handler: Arc<dyn DynamicEventHandler>) {
        let mut handlers = self.handlers.write().unwrap();
        handlers.entry(event_type.to_string())
            .or_default()
            .push(handler);
    }

    pub fn clone_sender(&self) -> SimpleEventSender {
        SimpleEventSender {
            event_queue: self.event_queue.clone(),
        }
    }

    pub fn start(&mut self) {
        if self.running.load(Ordering::Relaxed) {
            return;
        }

        self.running.store(true, Ordering::Relaxed);

        for worker_id in 0..self.config.worker_count {
            let running = self.running.clone();
            let event_queue = self.event_queue.clone();
            let handlers = self.handlers.clone();

            let handle = thread::Builder::new()
                .name(format!("simple-worker-{worker_id}"))
                .spawn(move || {
                    while running.load(Ordering::Relaxed) {
                        if let Some(event) = event_queue.dequeue() {
                            let event_type = event.event_type();
                            let handlers_guard = handlers.read().unwrap();
                            
                            if let Some(handler_list) = handlers_guard.get(event_type) {
                                if let Some(first_handler) = handler_list.first() {
                                    let _result = first_handler.handle_dynamic(&event);
                                    // 简化处理：只处理第一个匹配的handler
                                }
                            }
                            drop(handlers_guard);
                        } else {
                            thread::sleep(Duration::from_millis(1));
                        }
                    }
                })
                .expect("Failed to spawn worker thread");

            self.worker_handles.push(handle);
        }
    }

    pub fn stop(&mut self) {
        // 设置停止标志
        self.running.store(false, Ordering::SeqCst);
        
        // 等待所有worker线程停止
        while let Some(handle) = self.worker_handles.pop() {
            let _ = handle.join();
        }
        
        // 清理剩余的事件，避免内存泄漏
        while self.event_queue.dequeue().is_some() {
            // 丢弃剩余事件
        }
    }

    pub fn publish(&self, event: DynamicEvent) -> Result<(), DynamicEvent> {
        self.event_queue.enqueue(event)
    }
}